package cn.caplike.demo.repository.security;


import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;

/**
 * Description:
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2022-07-11 17:33
 */
public class SHA256Demo {

    public static void main(String[] args) {
        try {
            byte[] bytes = "A".getBytes();
            // 生成一个指定算法加密计算摘要
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(bytes);
            System.out.println(byteArrayToHexString(messageDigest.digest()));
            // System.out.println(HexTest.byteArrToHex(messageDigest.digest()));
            System.out.println(getSHA256Str("A".getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        // 559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd
        // 559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd
        // 559aead08264d5795d3909718cdd05abd49572e84fe55590eef31a88a08fdffd
    }

    public static String getSHA256Str(byte[] src){
        MessageDigest messageDigest;
        String encdeStr;
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            byte[] hash = messageDigest.digest(src);
            encdeStr = Hex.encodeHexString(hash);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return encdeStr;
    }

    private static String byteArrayToHexString(byte[] byteArray) {
        final StringBuilder builder = new StringBuilder();
        for (int idx = 0; byteArray != null && idx < byteArray.length; idx++) {
            String current = Integer.toHexString(byteArray[idx] & 0XFF);
            if (current.length() == 1) {
                builder.append("0");
            }
            builder.append(current);
        }
        return builder.toString().toLowerCase();
    }

    public static class HexTest {

        private static final char[] HexCharArr = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

        private static final String HexStr = "0123456789abcdef";

        public static String byteArrToHex(byte[] btArr) {
            char[] strArr = new char[btArr.length * 2];
            int i = 0;
            for (byte bt : btArr) {
                strArr[i++] = HexCharArr[bt>>>4 & 0xf];
                strArr[i++] = HexCharArr[bt & 0xf];
            }
            return new String(strArr);
        }

        public static byte[] hexToByteArr(String hexStr) {
            char[] charArr = hexStr.toCharArray();
            byte[] btArr = new byte[charArr.length / 2];
            int index = 0;
            for (int i = 0; i < charArr.length; i++) {
                int highBit = HexStr.indexOf(charArr[i]);
                int lowBit = HexStr.indexOf(charArr[++i]);
                btArr[index] = (byte) (highBit << 4 | lowBit);
                index++;
            }
            return btArr;
        }
    }
}
